<template>
  <div class="material-requisition">
    <el-card class="header-card">
      <div class="page-header">
        <div class="header-left">
          <h2>
            <el-icon><Box /></el-icon>
            生产领料管理
          </h2>
          <p>管理生产所需物料的领用和退料</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新建领料单
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="领料单号">
          <el-input v-model="searchForm.requisitionNo" placeholder="请输入领料单号" clearable />
        </el-form-item>
        <el-form-item label="工单号">
          <el-input v-model="searchForm.workOrderNo" placeholder="请输入工单号" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="已领料" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" stripe border v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="requisitionNo" label="领料单号" width="180" fixed />
        <el-table-column prop="workOrderNo" label="工单号" width="160" />
        <el-table-column prop="productName" label="产品名称" width="180" />
        <el-table-column prop="warehouseName" label="领料仓库" width="120" />
        <el-table-column prop="totalAmount" label="领料金额" width="120" align="right">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold">¥{{ row.totalAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="requisitioner" label="领料人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button link type="success" size="small" @click="handleApprove(row)" v-if="row.status === 'pending'">审核</el-button>
            <el-button link type="primary" size="small" @click="handleIssue(row)" v-if="row.status === 'approved'">领料</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)" v-if="row.status === 'pending'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination"
      />
    </el-card>

    <!-- 新建对话框 -->
    <el-dialog v-model="dialogVisible" title="新建领料单" width="1000px">
      <el-form :model="formData" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="领料单号">
              <el-input v-model="formData.requisitionNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工单号">
              <el-select v-model="formData.workOrderNo" placeholder="请选择工单" filterable>
                <el-option label="WO202501001" value="WO202501001" />
                <el-option label="WO202501002" value="WO202501002" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="领料仓库">
              <el-select v-model="formData.warehouseId" placeholder="请选择仓库">
                <el-option label="原材料仓" value="1" />
                <el-option label="辅料仓" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">物料明细</el-divider>
        <el-button type="primary" size="small" @click="addMaterial" style="margin-bottom: 10px">
          <el-icon><Plus /></el-icon> 添加物料
        </el-button>

        <el-table :data="formData.materials" border>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column label="物料名称" width="200">
            <template #default="{ row }">
              <el-select v-model="row.materialId" placeholder="选择" size="small" filterable>
                <el-option label="原料A" value="1" />
                <el-option label="原料B" value="2" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="150">
            <template #default="{ row }">
              <el-input v-model="row.specification" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="领料数量" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" :min="1" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template #default="{ row }">
              <el-input v-model="row.unit" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.price" :min="0" :precision="2" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120">
            <template #default="{ row }">
              <span>¥{{ (row.quantity * row.price).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ $index }">
              <el-button link type="danger" size="small" @click="removeMaterial($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Box, Plus, Search } from '@element-plus/icons-vue'

const searchForm = reactive({
  requisitionNo: '',
  workOrderNo: '',
  status: ''
})

const tableData = ref([])
const loading = ref(false)

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const dialogVisible = ref(false)
const formData = reactive({
  requisitionNo: '',
  workOrderNo: '',
  warehouseId: '',
  materials: []
})

const fetchData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        requisitionNo: 'MR202501001',
        workOrderNo: 'WO202501001',
        productName: '产品A',
        warehouseName: '原材料仓',
        totalAmount: 12500.50,
        status: 'pending',
        requisitioner: '张三',
        createTime: '2025-01-10 09:00:00'
      },
      {
        id: '2',
        requisitionNo: 'MR202501002',
        workOrderNo: 'WO202501002',
        productName: '产品B',
        warehouseName: '辅料仓',
        totalAmount: 8600.00,
        status: 'completed',
        requisitioner: '李四',
        createTime: '2025-01-11 10:00:00'
      }
    ]
    pagination.total = 2
    loading.value = false
  }, 500)
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    completed: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待审核',
    approved: '已审核',
    completed: '已领料'
  }
  return texts[status] || status
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(searchForm, { requisitionNo: '', workOrderNo: '', status: '' })
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.size = size
  fetchData()
}

const handlePageChange = (page) => {
  pagination.page = page
  fetchData()
}

const showAddDialog = () => {
  Object.assign(formData, {
    requisitionNo: 'MR' + Date.now(),
    workOrderNo: '',
    warehouseId: '',
    materials: []
  })
  dialogVisible.value = true
}

const handleView = (row) => {
  ElMessage.info('查看领料单：' + row.requisitionNo)
}

const handleApprove = (row) => {
  ElMessageBox.confirm('确定审核通过该领料单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('审核成功')
    fetchData()
  })
}

const handleIssue = (row) => {
  ElMessageBox.confirm('确定完成领料吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('领料成功')
    fetchData()
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该领料单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    fetchData()
  })
}

const addMaterial = () => {
  formData.materials.push({
    materialId: '',
    specification: '',
    quantity: 1,
    unit: '个',
    price: 0
  })
}

const removeMaterial = (index) => {
  formData.materials.splice(index, 1)
}

const handleSubmit = () => {
  ElMessage.success('保存成功')
  dialogVisible.value = false
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.material-requisition {
  padding: 20px;

  .header-card {
    margin-bottom: 20px;
    
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        h2 {
          display: flex;
          align-items: center;
          gap: 10px;
          margin: 0 0 10px 0;
          font-size: 24px;
          color: #303133;
        }

        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }

  .filter-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }
}
</style>

